package com.cqc.manage.service.Imp.business;


import cn.hutool.core.date.DateUtil;
import com.cqc.manage.dto.BusinessDto;
import com.cqc.manage.dto.EngineerBussinessDto;
import com.cqc.manage.entity.MessageBusiness;
import com.cqc.manage.repositories.MessageBusinessRepositories;
import com.cqc.manage.util.thrift.TTSocket;
import com.cqc.manage.util.thrift.ThriftClientConnectPoolFactory;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
//import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 收费通知类
 */
@Service
public class BusinessChargeNoticeService {

    private Logger LOG = LoggerFactory.getLogger(BusinessChargeNoticeService.class);

    @Autowired
    private ThriftClientConnectPoolFactory thriftClientConnectPoolFactory;

    @Autowired
    private MessageBusinessRepositories messageBusinessRepositories;


    /**
     * 生成收费通知
     * @param contractNo   合同编号
     * @param cost  费用
     */
    public String getBusChaNot(String contractNo,String cost){
        TTSocket ttSocket = null;
            try {
                ttSocket = thriftClientConnectPoolFactory.getConnect();

                String Pdf_File_Name = ttSocket.getService().getBusMge(contractNo,cost);

                LOG.info("查询信息：{}",Pdf_File_Name);
                thriftClientConnectPoolFactory.returnConnection(ttSocket);

//                pdf2multiImage("G:\\ca\\pycharm\\cqc\\pdf\\"+Pdf_File_Name,"G:\\ca\\manage\\chartNotice\\"+contractNo+".jpg");
                return Pdf_File_Name;
            }catch (Exception e){
                LOG.error(e.getMessage());
                if (ttSocket!=null){
                    thriftClientConnectPoolFactory.invalidateObject(ttSocket);
                }
                return null;
            }
    }

    /**
     * 生成多个业务的收费通知
     * @param businessDtoList   业务集合
     */
    public String getMultipleBusChaNot(List<BusinessDto> businessDtoList){
        TTSocket ttSocket = null;
        try {
            ttSocket = thriftClientConnectPoolFactory.getConnect();

            List<Map<String,String>> businessList = new ArrayList<>();
            for ( BusinessDto businessDto : businessDtoList){
                Map<String,String>  map = new HashMap<>();
                map.put("contractNo",businessDto.getContractNo());
                map.put("cost", businessDto.getCost());
                businessList.add(map);
            }
            String Pdf_File_Name = ttSocket.getService().getMultipleCheckNoice(businessList );

            LOG.info("查询信息：{}",Pdf_File_Name);
            thriftClientConnectPoolFactory.returnConnection(ttSocket);

            return Pdf_File_Name;
        }catch (Exception e){
            LOG.error(e.getMessage());
            if (ttSocket!=null){
                thriftClientConnectPoolFactory.invalidateObject(ttSocket);
            }
            return null;
        }
    }


    /**
     * @Description pdf转成一张图片
     * @created
     * @param pdfFile
     * @param outpath
     */
    public static void pdf2multiImage(String pdfFile, String outpath) {
        try {
            InputStream is = new BufferedInputStream(new FileInputStream(pdfFile));
            PDDocument pdf = PDDocument.load(is);
            int actSize  = pdf.getNumberOfPages();
            List<BufferedImage> piclist = new ArrayList<BufferedImage>();
            for (int i = 0; i < actSize; i++) {
                BufferedImage  image = new PDFRenderer(pdf).renderImageWithDPI(i,130, ImageType.RGB);
                piclist.add(image);
            }
            yPic(piclist, outpath);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 将宽度相同的图片，竖向追加在一起 ##注意：宽度必须相同
     * @param piclist  文件流数组
     * @param outPath  输出路径
     */
    public static void yPic(List<BufferedImage> piclist, String outPath) {// 纵向处理图片
        if (piclist == null || piclist.size() <= 0) {
            System.out.println("图片数组为空!");
            return;
        }
        try {
            int height = 0, // 总高度
                    width = 0, // 总宽度
                    _height = 0, // 临时的高度 , 或保存偏移高度
                    __height = 0, // 临时的高度，主要保存每个高度
                    picNum = piclist.size();// 图片的数量
            int[] heightArray = new int[picNum]; // 保存每个文件的高度
            BufferedImage buffer = null; // 保存图片流
            List<int[]> imgRGB = new ArrayList<int[]>(); // 保存所有的图片的RGB
            int[] _imgRGB; // 保存一张图片中的RGB数据
            for (int i = 0; i < picNum; i++) {
                buffer = piclist.get(i);
                heightArray[i] = _height = buffer.getHeight();// 图片高度
                if (i == 0) {
                    width = buffer.getWidth();// 图片宽度
                }
                height += _height; // 获取总高度
                _imgRGB = new int[width * _height];// 从图片中读取RGB
                _imgRGB = buffer.getRGB(0, 0, width, _height, _imgRGB, 0, width);
                imgRGB.add(_imgRGB);
            }
            _height = 0; // 设置偏移高度为0
            // 生成新图片
            BufferedImage imageResult = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            for (int i = 0; i < picNum; i++) {
                __height = heightArray[i];
                if (i != 0) _height += __height; // 计算偏移高度
                imageResult.setRGB(0, _height, width, __height, imgRGB.get(i), 0, width); // 写入流中
            }
            File outFile = new File(outPath);
            ImageIO.write(imageResult, "jpg", outFile);// 写图片
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /***
     * 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
     * @param imgFile
     * @return
     */
    public static String ImageToBase64ByLocal(String imgFile) {
        InputStream in = null;
        byte[] data = null;
        // 读取图片字节数组
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
//        BASE64Encoder encoder = new BASE64Encoder();
        // 返回Base64编码过的字节数组字符串
//        return encoder.encode(data);
        return null;
    }


    /**
     * 查询协议金额为了0的业务，一次判断没有发送收费通知
     * @param engineerBussinessDto
     */
    public void getChargeNoticeBusiness(EngineerBussinessDto engineerBussinessDto){
        Specification<MessageBusiness> specification = new Specification<MessageBusiness>() {
            @Override
            public Predicate toPredicate(Root<MessageBusiness> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                predicateList.add(criteriaBuilder.equal(root.get("agreementAmount"), "0.00"));
                predicateList.add(criteriaBuilder.equal(root.get("invoice"), "0.0"));
//                predicateList.add(criteriaBuilder.equal(root.get("engineer"), userAccount));
                predicateList.add(criteriaBuilder.like(root.get("engineer"), "%"+engineerBussinessDto.getEngLimsAccount()+"%"));
                predicateList.add(criteriaBuilder.notLike(root.get("client"),"%中认尚动%"));
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        Page<MessageBusiness> all = messageBusinessRepositories.findAll(specification, PageRequest.of(engineerBussinessDto.getPage() - 1, engineerBussinessDto.getSize()));
        List<BusinessDto> businessDtoList = BusinessInvoiceService.setBusinessDto(all.getContent());
        LOG.info("未发送收费通知的查询结果:{}",businessDtoList);
        engineerBussinessDto.setList(businessDtoList);
        engineerBussinessDto.setTotal(all.getTotalElements());
    }







    public static void main(String[] args){
//        pdf2multiImage();

//        doc3pdf("C:\\Users\\ca\\Desktop\\fsdownload\\E2021050573--2021-05-15.docx","G:\\1\\234.pdf");
//        String s = ImageToBase64ByLocal("G:\\1\\234.jpg");
//        System.out.println(s);

    }



}
